import axios from "axios";
import Vue from "vue";
import store from "@/store";
const JSON_HEADER = "application/json;charset=UTF-8";
const FILE_HEADER = "multipart/form-data";
var IS_FILE = false;
axios.defaults.withCredentials = false;
const request = axios.create({
  timeout: 15000, // 请求超时时间
  baseURL: "/ka-moot-service/api",
});
// request拦截器
request.interceptors.request.use(
  (config) => {
    Vue.prototype.$toast.loading({
      duration: 0, // 持续展示 toast
      message: "加载中...",
      forbidClick: true,
    });
    debugger;
    if (store.getters.getUserInfo) {
      config.headers["AccessToken"] = store.getters.getUserInfo.token; // 增加AccessToken
    }
    config.headers["Content-Type"] = IS_FILE ? FILE_HEADER : JSON_HEADER;
    return config;
  },
  (error) => {
    Promise.reject(error);
    Vue.prototype.$toast.clear();
  }
);

// respone拦截器
request.interceptors.response.use(
  (response) => {
    Vue.prototype.$toast.clear();
    const res = response.data;
    if (res) {
      if (res.code == 0) {
        return res;
      }
    } else {
      return Promise.reject("");
    }
  },
  (error) => {
    Vue.prototype.$toast.clear();
    const res = error.response;
    return Promise.reject(res);
  }
);
export const post = function(ops) {
  IS_FILE = false;
  return request({
    method: "post",
    ...ops,
  });
};
export const get = function(ops) {
  IS_FILE = false;
  return request({
    method: "get",
    ...ops,
  });
};
export const upload = function(ops) {
  IS_FILE = true;
  return request({
    method: "post",
    ...ops,
  });
};

export default request;
